package com.openyelp.webstore.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import com.openyelp.webstore.action.UpConfig;

public class FileBackup {

	public static void BackupFile(File file,UpConfig config){
		
		String ext = FilenameUtils.getExtension(file.getName()).toLowerCase(
				Locale.ENGLISH);
		String savePath="D:\\backupfile\\";
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		if (!uploadDir.isDirectory()) {
		}
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
		}
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("jpeg", "image");
		extMap.put("gif", "image");
		extMap.put("jpg", "image");
		extMap.put("png", "image");
		extMap.put("bmp", "image");
		
		
		extMap.put("flv", "flash");
		extMap.put("swf", "flash");
		
		extMap.put("mp3", "media");
		extMap.put("wav", "media");
		extMap.put("wmv", "media");
		extMap.put("mid", "media");
		extMap.put("avi", "media");
		extMap.put("mpg", "media");
		extMap.put("asf", "media");
		extMap.put("rm", "media");
		extMap.put("rmvb", "media");

		extMap.put("file", "doc");
		extMap.put("docx", "doc");
		extMap.put("xls", "doc");
		extMap.put("xlsx", "doc");
		extMap.put("ppt", "doc");
		extMap.put("htm", "doc");
		extMap.put("html", "doc");
		extMap.put("txt", "doc");
		extMap.put("zip", "doc");
		extMap.put("rar", "doc");
		extMap.put("gz", "doc");
		extMap.put("bz2", "doc");
		savePath += config.getApp() + "/";
		File appDirFile = new File(savePath);
		if (!appDirFile.exists()) {
			appDirFile.mkdirs();
		}
		String dirName = extMap.get(ext);
		if (dirName == null) {
			dirName = "image";
		}
		// 创建文件夹
		savePath += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File uploadedFile = new File(savePath, file.getName());
	    ;
	    try {
			FileUtils.copyFile(file, uploadedFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		//BackupFile(new File("e:\\正信营业执照（正本）.jpg"));
	}
}
